import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, Image, SafeAreaView, StatusBar, TouchableWithoutFeedback, Keyboard, ActivityIndicator } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons, MaterialIcons, FontAwesome } from '@expo/vector-icons';
import { Link, router } from 'expo-router';
import { Checkbox } from 'react-native-paper';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAppDispatch, useAppSelector } from './store/hooks';
import { loginUser, clearError } from './store/userSlice';

// 登录页面组件
export default function LoginScreen() {
  const insets = useSafeAreaInsets(); // 获取安全区域的尺寸
  
  const [studentId, setStudentId] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  
  const dispatch = useAppDispatch();
  const { loading, error, isAuthenticated } = useAppSelector(state => state.user);

  // 成功登录后重定向到主页
  useEffect(() => {
    if (isAuthenticated) {
      router.replace('/(tabs)');
    }
  }, [isAuthenticated]);

  // 显示错误提示
  useEffect(() => {
    if (error) {
      Alert.alert('登录失败', error, [
        { text: '确定', onPress: () => dispatch(clearError()) }
      ]);
    }
  }, [error, dispatch]);

  // 显示社交登录功能开发中的提示
  const showDevelopingAlert = () => {
    Alert.alert(
      '功能开发中',
      '该功能正在开发中，敬请期待！',
      [{ text: '确定', style: 'default' }]
    );
  };

  // 处理登录按钮点击
  const handleLogin = () => {
    if (!studentId || studentId.length !== 9 || !/^\d+$/.test(studentId)) {
      Alert.alert('提示', '请输入9位数字学号');
      return;
    }
    
    if (!password) {
      Alert.alert('提示', '请输入密码');
      return;
    }

    // 调用登录API
    dispatch(loginUser({ studentId, userPassword: password }));
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View style={styles.container}>
        <StatusBar barStyle="light-content" />
        
        {/* 顶部渐变背景区域 */}
        <LinearGradient
          colors={['#9c27b0', '#5e35b1', '#3949ab']}
          style={[
            styles.header,
            { paddingTop: insets.top + 20 } // 添加顶部安全区域的padding
          ]}
        >
          <View style={styles.headerTextContainer}>
            <Text style={styles.welcomeText}>欢迎回来</Text>
            <Text style={styles.subHeaderText}>请登录您的账户继续</Text>
          </View>
        </LinearGradient>

        {/* 表单区域 */}
        <View style={styles.formContainer}>
          {/* 学号输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>学号</Text>
            <View style={styles.inputContainer}>
              <MaterialIcons name="badge" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请输入9位数字学号"
                keyboardType="numeric"
                maxLength={9}
                value={studentId}
                onChangeText={setStudentId}
                editable={!loading}
              />
            </View>
          </View>

          {/* 密码输入框 */}
          <View style={styles.inputGroup}>
            <Text style={styles.label}>密码</Text>
            <View style={styles.inputContainer}>
              <Ionicons name="lock-closed" size={20} color="#888" style={styles.inputIcon} />
              <TextInput
                style={styles.input}
                placeholder="请输入密码"
                secureTextEntry={!showPassword}
                value={password}
                onChangeText={setPassword}
                editable={!loading}
              />
              <TouchableOpacity 
                style={styles.passwordToggle}
                onPress={() => setShowPassword(!showPassword)}
                disabled={loading}
              >
                <Ionicons name={showPassword ? "eye" : "eye-off"} size={20} color="#888" />
              </TouchableOpacity>
            </View>
          </View>

          {/* 记住我和忘记密码 */}
          <View style={styles.rememberForgotRow}>
            <View style={styles.checkboxContainer}>
              <Checkbox
                status={rememberMe ? 'checked' : 'unchecked'}
                onPress={() => setRememberMe(!rememberMe)}
                color="#5e35b1"
                disabled={loading}
              />
              <Text style={styles.rememberMeText}>记住我</Text>
            </View>
            <TouchableOpacity onPress={() => router.replace('/forgot-password')} disabled={loading}>
              <Text style={styles.forgotPasswordText}>忘记密码?</Text>
            </TouchableOpacity>
          </View>

          {/* 登录按钮 */}
          <TouchableOpacity 
            style={[styles.loginButton, loading && styles.loginButtonDisabled]} 
            onPress={handleLogin}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="#ffffff" size="small" />
            ) : (
              <Text style={styles.loginButtonText}>登录</Text>
            )}
          </TouchableOpacity>

          {/* 其他登录方式 - 调整间距 */}
          <View style={[styles.otherLoginContainer, { marginTop: 5, marginBottom: 8 }]}>
            <View style={styles.divider}></View>
            <Text style={styles.otherLoginText}>其他登录方式</Text>
            <View style={styles.divider}></View>
          </View>

          {/* 社交登录按钮 - 调整间距 */}
          <View style={[styles.socialButtonsContainer, { marginVertical: 8 }]}>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="weixin" size={24} color="#09BB07" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="qq" size={24} color="#2196F3" />
            </TouchableOpacity>
            <TouchableOpacity style={styles.socialButton} onPress={showDevelopingAlert} disabled={loading}>
              <FontAwesome name="weibo" size={24} color="#E91E63" />
            </TouchableOpacity>
          </View>

          {/* 注册链接 */}
          <View style={[styles.registerContainer, { marginBottom: Math.max(insets.bottom, 16) }]}>
            <Text style={styles.registerText}>还没有账户? </Text>
            <TouchableOpacity onPress={() => router.replace("/register" as any)} disabled={loading}>
              <Text style={styles.registerLink}>立即注册</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f9f9f9',
  },
  header: {
    minHeight: 180,
    paddingHorizontal: 24,
  },
  headerTextContainer: {
    marginTop: 20,
  },
  welcomeText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: 8,
  },
  subHeaderText: {
    fontSize: 16,
    color: 'rgba(255, 255, 255, 0.8)',
  },
  formContainer: {
    flex: 1,
    backgroundColor: '#ffffff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    marginTop: -20,
    paddingHorizontal: 24,
    paddingTop: 24, // 减少顶部内边距
  },
  inputGroup: {
    marginBottom: 16, // 减少输入框组间距
  },
  label: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 8,
    color: '#333',
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    backgroundColor: '#f9f9f9',
    height: 50,
  },
  inputIcon: {
    paddingHorizontal: 12,
  },
  input: {
    flex: 1,
    height: 50,
    fontSize: 16,
    color: '#333',
  },
  passwordToggle: {
    padding: 12,
  },
  rememberForgotRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20, // 减少间距
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  rememberMeText: {
    fontSize: 14,
    color: '#666',
  },
  forgotPasswordText: {
    fontSize: 14,
    color: '#5e35b1',
    fontWeight: '500',
  },
  loginButton: {
    backgroundColor: '#5e35b1',
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12, // 减少登录按钮底部间距
  },
  loginButtonDisabled: {
    backgroundColor: '#9e9e9e',
  },
  loginButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  otherLoginContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 16,
  },
  divider: {
    flex: 1,
    height: 1,
    backgroundColor: '#e0e0e0',
  },
  otherLoginText: {
    marginHorizontal: 16,
    color: '#666',
    fontSize: 14,
  },
  socialButtonsContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginVertical: 16,
  },
  socialButton: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 1.5,
    elevation: 2,
  },
  registerContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 8,
  },
  registerText: {
    color: '#666',
    fontSize: 14,
  },
  registerLink: {
    color: '#5e35b1',
    fontWeight: '500',
    fontSize: 14,
  },
}); 